const express=require('express')
const path=require('path')
const bodyParser=require('body-parser')
const router=require('./route/router')
const cors=require('cors')
const expressJwt=require('express-jwt')
const tokenPo=require('./constant/tokenPo')
const app=express()
const morgan=require('morgan')
const writelog=require('./util/writelog')
//写入日志
app.use(morgan('combined',{stream:writelog}))
//输出简单日志
app.use(morgan('dev',{stream:process.stdout}))
// 解决跨域问题
app.use(cors())
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
app.use(expressJwt({secret:tokenPo.secretKey,algorithms:['HS256'],
//这个getToken必须要(在jwt 前不加'Bearer '时)
// getToken:(req)=>{
//   var token=req.headers.authorization
//   if(token){
//     return token
//   }
//   return null
// },
credentialsRequired: false}).unless({
  path:['/user/login','/user/logout','/user/register','/cos/costoken']
}))
app.use(function (err, req, resp, next) {
  if (err.name == 'UnauthorizedError') { 
    //  这个需要根据自己的业务逻辑来处理（ 具体的err值 请看下面）
    let data = {};
    data.message = 'token验证失败';
    data.code = 401;
    err.name=''
    resp.status(200).json(data); //返回失败信息
  }
});

app.use('/public/',express.static(path.join(__dirname,'/public/')))
app.use(router)
app.use((err,req,resp,next)=>{
    throw new Error(err) 
})
app.listen(3000,()=>{
  console.log('app run start......')
})
//老版本处理跨域
// app.all("/*", function(req, res, next) {
//   // 跨域处理
//   res.header("Access-Control-Allow-Origin", "*");
//   res.header("Access-Control-Allow-Headers", "X-Requested-With");
//   res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
//   res.header("X-Powered-By", ' 3.2.1');
//   res.header("Content-Type", "application/json;charset=utf-8");
//   next(); // 执行下一个路由
// })